<!--
 * Copyright © 2023
 * @Author: zhangxiang
 * @Date: 2023-09-21 16:34:18
 * @LastEditors: 976901273@qq.com
 * @LastEditTime: 2023-11-22 10:10:57
 * @Description:
 *
-->

<template>
<MyContainer class="container">
      <MyHeader class="header">
      <el-input
        v-model="searchKey"
        style="width: 200px; margin-right: 20px"
        size="medium"
        class="input"
        placeholder="请输入关键字进行过滤"
        clearable
        @clear="clearClick"
        @keyup.enter.native="initTableData"
      />
      <el-button
        size="medium"
        type="primary"
        @click="initTableData"
      >查询</el-button>
      <el-button size="medium" @click="resetClick">重置</el-button>
      <div style="position:relative;left:200px">
        <el-button
          style="margin-left:50px"
            size="medium"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="addInfo=true"
          >生成报表</el-button>
          <el-button
          style="margin-left:50px"
            size="medium"
            type="success"
            icon="el-icon-download"
            @click="reportdExportList"
          >导出</el-button>
        <el-button
          style="margin-left:50px"
            size="medium"
            type="warning"
            icon="el-icon-delete"
            @click="deleteReport"
          >删除</el-button>
      </div>
    </MyHeader>
    <MyMain class="main">
      <el-table
        class="common-table"
        :data="dataList"
        @selection-change='selectRow'
        stripe
        header-cell-class-name="listHeaderCell"
        :header-cell-style="{ color: '#696969' }"
      >
        <el-table-column
          type="selection"
          width="100">
        </el-table-column>
        <el-table-column
          prop="reportName"
          label="报表名称"
          show-overflow-tooltip
        />
        <el-table-column
          prop="reportType"
          label="报表类型"
          show-overflow-tooltip
        />
        <el-table-column
          prop="user"
          label="创建人"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="生成时间"
          show-overflow-tooltip
        />
      </el-table>
      <el-row type="flex" justify="end" style="margin-top: 30px">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :page-sizes="[10, 15, 20]"
          :page-size="pageSize"
          :current-page.sync="pageNum"
          :total="totalCount"
          @current-change="changePage"
          @size-change="sizeChange"
        />
      </el-row>
    </MyMain>
    <el-dialog title="生成报表" :visible.sync="addInfo" width="500px" :close-on-click-modal="false"  :show-close="false" style="padding:50px">
            <el-form :model="form" label-width="120px" ref="formRef" :rules='formRules'>
                <el-form-item label="报表名称" prop="reportName" >
                  <el-input style="width:310px" v-model="form.reportName"></el-input>
                </el-form-item>
                <el-form-item label="报表类型" prop="reportType" >
                    <el-select v-model="form.reportType" placeholder="请选择" @change="changeReportType" style="width:310px">
                      <el-option
                    
                        v-for="item in reportTypeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="集群" prop="cloudClusterObj" v-if="form.reportType==='事件'">
                  <CloudCluster
                    :cloud-cluster-obj.sync="cloudClusterObj"
                    :cloud-vendor-title="''"
                    :k8s-cluster-name-title="''"
                  />
                </el-form-item>
                <el-form-item label="告警级别" prop="alarmLevel" v-if="form.reportType==='告警'">
                    <el-select v-model="form.alarmLevel" placeholder="请选择" style="width:310px">
                      <el-option
                        v-for="item in alarmLevelOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户" prop="userName" v-if="form.reportType==='日志'" >
                    <el-select v-model="form.userName" placeholder="请选择" style="width:310px" disabled>
                      <el-option
                        v-for="item in userNameOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="操作" prop="operationType" v-if="form.reportType==='日志'" >
                    <el-select v-model="form.operationType" placeholder="请选择" style="width:310px">
                      <el-option
                        v-for="item in operationTypeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间"  prop="startTime">
                    <el-date-picker
                      type="date"
                      placeholder="请选择开始时间"
                      format="yyyy-MM-dd"
                      style="width: 310px;"
                      value-format="timestamp"
                      v-model="form.startTime">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                      type="date"
                      format="yyyy-MM-dd"
                      style="width: 310px;"
                      placeholder="请选择结束时间"
                      value-format="timestamp"
                      v-model="form.endTime">
                    </el-date-picker>
                </el-form-item>
                <el-form-item style="text-align:right">
                  <el-button @click="addCancel()">取 消</el-button>
                  <el-button type="primary" @click="addConfirm()" :disabled="returnResult">确 认</el-button>
                </el-form-item>
            </el-form>
      </el-dialog>
</MyContainer>
</template>

<script>
import { mapGetters } from 'vuex'
import pagePermissionMixin from '@/views/mixin/pagePermission.js'
import pageQueryMixin from '@/views/mixin/pageQuery.js'
import MyContainer from '@/components/Layout/MyContainer.vue'
import MyHeader from '@/components/Layout/MyHeader.vue'
import MyMain from '@/components/Layout/MyMain.vue'
import { createReportAlarm,createReportLog,createReportEvent,getReportList,reportdDelete,reportdExport } from '@/api/cnap/statis-analysis'
import CloudCluster from '@/components/CloudCluster'
export default {
  name: 'SystemMonitorCNResPM',
  components: {
    MyContainer,
    MyHeader,
    MyMain,
    CloudCluster,
  },
  mixins: [pagePermissionMixin, pageQueryMixin],
  data() {
    return {
      returnResult:false,
      searchKey:'',
      pageNum:0,
      pageSize:10,
      totalCount:0,
      dataList:[],
      checkList:[],
      loadName:'',
      addInfo:false,
      cloudClusterObj: {
        cloudVendor: '', // 云服务商
        accountName: '', // 云账户
        clusterName: '' // 集群名称
      },
      reportTypeOptions:[
        {
          value: '事件',
          label: '事件'
        },
        {
          value: '告警',
          label: '告警'
        },
        {
          value: '日志',
          label: '日志'
        },
      ],
      alarmLevelOptions:[
        {
          value: '紧急',
          label: '紧急'
        },
        {
          value: '重要',
          label: '重要'
        },
        {
          value: '次要',
          label: '次要'
        },
        {
          value: '提示',
          label: '提示'
        }
      ],
      userNameOptions:[
        {
          value: 'admin',
          label: 'admin'
        }
      ],
      operationTypeOptions:[
          {
            value: '登录',
            label: '登录'
          },
          {
            value: '退出',
            label: '退出'
          },
          {
            value: '添加',
            label: '添加'
          },
          {
            value: '删除',
            label: '删除'
          },
          {
            value: '其他',
            label: '其他'
          }
        ],
      form:{
        reportName:'',
        reportType:'',
        startTime:'',
        endTime:'',
        alarmLevel:'',
        userName:this.userName,
        operationType:'',
      },
      formRules: {
            reportName: [
                {required: true, message: '报表名称为必填项', trigger: 'blur' }
            ],
            reportType: [
                {required: true, message: '报表类型为必填项', trigger: 'blur' }
            ],
            startTime: [
              {
                validator: this.validationDateFrom
              }
            ],
            endTime: [
              {
                validator: this.validationDateTo
              }
            ]
        },
    }
  },
  created() {},
    computed: {
    /**
     * @description: 用户名
     * @return {*}
     */
    ...mapGetters(['userName']),
  },
  mounted(){
    this.initTableData()
  },
  methods: {
        // 自定义验证规则(校验开始日期)
    validationDateFrom: function (rule, value, callback) {
      console.log(value)
      // 比较时间戳(进行运算的时候会自动转换成时间戳进行运算，不运算的时候，显示中国标准时间格式)
      if (
        this.form.endTime - value <= 0 &&
        this.form.endTime &&
        value
      ) {
        return callback(new Error('*开始时间不能大于结束时间'))
      }
      callback()
    },
    // 自定义验证规则(校验截止日期)
    validationDateTo: function (rule, value, callback) {
      console.log(value)
      // 比较时间戳(进行运算的时候会自动转换成时间戳进行运算，不运算的时候，显示中国标准时间格式)
      if (
          (value) -   (this.form.startTime) <= 0 &&
        this.form.endTime &&
        value
      ) {
        return callback(new Error('*结束时间不能小于开始时间'))
      } callback()
    },
        // 当开始时间变化时,需要重新校验
    handelDateFrom (value) {
      console.log(value)
      if (
          (this.form.endTime) -   (value) > 0 &&
        this.form.endTime &&
        value
      ) {
        // 重新校验
        this.$refs.formRef.validate()
      }
    },
    handelDateTo (value) {
      console.log(value)
      if (
          (value) -   (this.form.startTime) > 0 &&
        this.form.startTime &&
        value
      ) {
        this.$refs.formRef.validate()
      }
    },
    changeReportType(){
      this.$refs.formRef.validate()
    },
    addConfirm(){
      this.$refs['formRef'].validate((valid) => {
                if (valid){
                  this.returnResult = true
                  let params = {
                    reportName :this.form.reportName,
                    reportType :this.form.reportType,
                    userName :this.userName,
                  }
                  let searchParam = {}
                  if(this.form.reportType === '告警'){
                    searchParam = {
                      alarmLevel: this.form.alarmLevel,
                      endTime: this.form.endTime/1000,
                      startTime: this.form.startTime/1000,
                    }
                    params.searchParam = searchParam
                    createReportAlarm(params).then(res => {
                      this.returnResult = false
                      if(res.code===200){
                        this.$message.success('生成成功')
                        this.addCancel()
                        this.initTableData()
                      }else{
                        this.$message.error(res.message)
                      }
                    })
                  }else if(this.form.reportType === '事件'){
                    searchParam = {
                      cloudVendor: this.cloudClusterObj.cloudVendor,
                      clusterName: this.cloudClusterObj.clusterName,
                      endTime: this.form.endTime/1000,
                      startTime: this.form.startTime/1000,
                    }
                    params.searchParam = searchParam
                    createReportEvent(params).then(res => {
                      this.returnResult = false
                      if(res.code===200){
                        this.$message.success('生成成功')
                        this.addCancel()
                        this.initTableData()
                      }else{
                        this.$message.error(res.message)
                      }
                    })
                  }else if(this.form.reportType === '日志'){
                    searchParam = {
                      operationType: this.form.operationType,
                      endTime: this.form.endTime/1000,
                      startTime: this.form.startTime/1000,
                    }
                    params.searchParam = searchParam
                    createReportLog(params).then(res => {
                      if(res.code===200){
                        this.returnResult = false
                        this.$message.success('生成成功')
                        this.addCancel()
                        this.initTableData()
                      }else{
                        this.$message.error(res.message)
                      }
                    })
                  }
                }         
            });
    },
    addCancel(){
      this.form={
        reportName:'',
        reportType:'',
        startTime:'',
        endTime:'',
        alarmLevel:'',
        userName:this.userName,
        operationType:'',
      }
      this.cloudClusterObj = {
        cloudVendor: '', // 云服务商
        accountName: '', // 云账户
        clusterName: '' // 集群名称
      },
      this.addInfo = false
    },
    initTableData(){
      let params = {
          key: this.searchKey,
          pageNo: this.pageNum,
          pageSize: this.pageSize
      }
      getReportList(params).then(res => {
        this.dataList = res.data.data// 返回数据在res.data.data中
        this.totalCount = res.data.totalSize
      })
    },
    resetClick(){
      this.searchKey = ''
      this.initTableData()
    },
    changePage(val){
      this.pageNum = val
      this.initTableData()
    },
    sizeChange(val){
      this.pageSize = val
      this.initTableData()
    },
    selectRow(val){
          this.checkList = []
          this.loadName = val[0].reportName
          val.forEach(element => {
            this.checkList.push(element.id)
          });
        },
    deleteReport(){
      if(this.checkList.length===0){
        this.$message.info("请选择数据")
        return
      }
      reportdDelete(this.checkList).then(res => {
        if(res.code===200){
          this.$message.success('删除成功')
          this.checkList = []
          this.initTableData()
        }else{
          this.$message.error(res.message)
        }
      })
    },
    reportdExportList(){
      if(this.checkList.length===0){
        this.$message.info("请选择数据")
        return
      }
      reportdExport(this.checkList).then(response => {
          this.$message.success('导出成功')
          const fileNames =
            response.headers['content-disposition'].split("filename*=utf-8''") // 读取文件名
          const fileName =
            fileNames.length > 1
              ? decodeURIComponent(fileNames[1])
              : this.loadName+'报表.zip' // 解析文件名
          const blob = new Blob([response.data], {
            type: 'application/zip'
          }) // 新建blob
          const elementA = document.createElement('a') // 创建 element a
          elementA.style.display = 'none' // 设置不可见
          elementA.href = window.URL.createObjectURL(blob) // 设置href
          elementA.download = fileName // 设置名称
          document.body.appendChild(elementA) // 添加到body
          elementA.click() // 模拟点击
          window.URL.revokeObjectURL(elementA.href) // 释放内存
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.container {
}
</style>
